"use strict";
cc._RF.push(module, '1a7f38OF3BCyYb8nSkf3Ty8', 'HttpRequest');
// script/Core/Libs/HttpRequest.ts

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpRequest = exports.HttpEvent = void 0;
var Config_1 = require("../../Config/Config");
var error = cc.error, warn = cc.warn;
var urls = {}; // 当前请求地址集合
var reqparams = {}; // 请求参数
/** 请求事件 */
var HttpEvent;
(function (HttpEvent) {
    /** 断网 */
    HttpEvent["NO_NETWORK"] = "http_request_no_network";
    /** 未知错误 */
    HttpEvent["UNKNOWN_ERROR"] = "http_request_unknown_error";
    /** 请求超时 */
    HttpEvent["TIMEOUT"] = "http_request_timout";
})(HttpEvent = exports.HttpEvent || (exports.HttpEvent = {}));
/** HTTP请求 */
var HttpRequest = /** @class */ (function () {
    function HttpRequest() {
        /** 服务器地址 */
        this.server = "";
        /** 请求超时时间 */
        this.timeout = -1;
        this.server = Config_1.GameParams.RequestHost;
        this.timeout = Config_1.GameParams.RequestTimeOut;
    }
    /**
     * HTTP GET请求
     * @param name                  协议名
     * @param completeCallback      请求完整回调方法
     * @param errorCallback         请求失败回调方法
     * @example
    var complete = function(response){
        console.log(response);
    }
    var error = function(response){
        console.log(response);
    }
    oops.http.get(name, complete, error);
     */
    HttpRequest.prototype.get = function (name, completeCallback, errorCallback) {
        this.sendRequest(name, null, false, completeCallback, errorCallback);
    };
    /**
     * HTTP GET请求
     * @param name                  协议名
     * @param params                查询参数
     * @param completeCallback      请求完整回调方法
     * @param errorCallback         请求失败回调方法
     * @example
    var param = '{"uid":12345}'
    var complete = function(response){
        var jsonData = JSON.parse(response);
        var data = JSON.parse(jsonData.Data);
        console.log(data.Id);
    }
    var error = function(response){
        console.log(response);
    }
    oops.http.getWithParams(name, param, complete, error);
     */
    HttpRequest.prototype.getWithParams = function (name, params, completeCallback, errorCallback) {
        this.sendRequest(name, params, false, completeCallback, errorCallback);
    };
    /**
     * HTTP GET请求非文本格式数据
     * @param name                  协议名
     * @param completeCallback      请求完整回调方法
     * @param errorCallback         请求失败回调方法
     */
    HttpRequest.prototype.getByArraybuffer = function (name, completeCallback, errorCallback) {
        this.sendRequest(name, null, false, completeCallback, errorCallback, 'arraybuffer', false);
    };
    /**
     * HTTP GET请求非文本格式数据
     * @param name                  协议名
     * @param params                查询参数
     * @param completeCallback      请求完整回调方法
     * @param errorCallback         请求失败回调方法
     */
    HttpRequest.prototype.getWithParamsByArraybuffer = function (name, params, completeCallback, errorCallback) {
        this.sendRequest(name, params, false, completeCallback, errorCallback, 'arraybuffer', false);
    };
    /**
     * HTTP POST请求
     * @param name                  协议名
     * @param params                查询参数
     * @param completeCallback      请求完整回调方法
     * @param errorCallback         请求失败回调方法
     * @example
    var param = '{"LoginCode":"donggang_dev","Password":"e10adc3949ba59abbe56e057f20f883e"}'
    var complete = function(response){
        var jsonData = JSON.parse(response);
        var data = JSON.parse(jsonData.Data);
        console.log(data.Id);
    }
    var error = function(response){
        console.log(response);
    }
    oops.http.post(name, param, complete, error);
     */
    HttpRequest.prototype.post = function (name, params, completeCallback, errorCallback) {
        this.sendRequest(name, params, true, completeCallback, errorCallback);
    };
    /** 取消请求中的请求 */
    HttpRequest.prototype.abort = function (name) {
        var xhr = urls[this.server + name];
        if (xhr) {
            xhr.abort();
        }
    };
    /**
     * 获得字符串形式的参数
     */
    HttpRequest.prototype.getParamString = function (params) {
        var result = "";
        for (var name in params) {
            var data = params[name];
            if (data instanceof Object) {
                for (var key in data)
                    result += key + "=" + data[key] + "&";
            }
            else {
                result += name + "=" + data + "&";
            }
        }
        return result.substr(0, result.length - 1);
    };
    /**
     * Http请求
     * @param name(string)              请求地址
     * @param params(JSON)              请求参数
     * @param isPost(boolen)            是否为POST方式
     * @param callback(function)        请求成功回调
     * @param errorCallback(function)   请求失败回调
     * @param responseType(string)      响应类型
     */
    HttpRequest.prototype.sendRequest = function (name, params, isPost, completeCallback, errorCallback, responseType, isOpenTimeout, timeout) {
        var _this = this;
        if (isOpenTimeout === void 0) { isOpenTimeout = true; }
        if (timeout === void 0) { timeout = this.timeout; }
        if (name == null || name == '') {
            error("请求地址不能为空");
            return;
        }
        var url, newUrl, paramsStr;
        if (name.toLocaleLowerCase().indexOf("http") == 0) {
            url = name;
        }
        else {
            url = this.server + name;
        }
        if (params) {
            paramsStr = this.getParamString(params);
            if (url.indexOf("?") > -1)
                newUrl = url + "&" + paramsStr;
            else
                newUrl = url + "?" + paramsStr;
        }
        else {
            newUrl = url;
        }
        if (urls[newUrl] != null && reqparams[newUrl] == paramsStr) {
            warn("\u5730\u5740\u3010" + url + "\u3011\u5DF2\u6B63\u5728\u8BF7\u6C42\u4E2D\uFF0C\u4E0D\u80FD\u91CD\u590D\u8BF7\u6C42");
            return;
        }
        var xhr = new XMLHttpRequest();
        // 防重复请求功能
        urls[newUrl] = xhr;
        reqparams[newUrl] = paramsStr;
        if (isPost) {
            xhr.open("POST", url);
        }
        else {
            xhr.open("GET", newUrl);
        }
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var data = {};
        data.url = url;
        data.params = params;
        // 请求超时
        if (isOpenTimeout) {
            xhr.timeout = timeout;
            xhr.ontimeout = function () {
                _this.deleteCache(newUrl);
                data.event = HttpEvent.TIMEOUT;
                if (errorCallback)
                    errorCallback(data);
            };
        }
        xhr.onloadend = function (a) {
            if (xhr.status == 500) {
                _this.deleteCache(newUrl);
                if (errorCallback == null)
                    return;
                data.event = HttpEvent.NO_NETWORK; // 断网
                if (errorCallback)
                    errorCallback(data);
            }
        };
        xhr.onerror = function () {
            _this.deleteCache(newUrl);
            if (errorCallback == null)
                return;
            if (xhr.readyState == 0 || xhr.readyState == 1 || xhr.status == 0) {
                data.event = HttpEvent.NO_NETWORK; // 断网 
            }
            else {
                data.event = HttpEvent.UNKNOWN_ERROR; // 未知错误
            }
            if (errorCallback)
                errorCallback(data);
        };
        xhr.onreadystatechange = function () {
            if (xhr.readyState != 4)
                return;
            _this.deleteCache(newUrl);
            if (xhr.status == 200) {
                if (completeCallback) {
                    if (responseType == 'arraybuffer') {
                        // 加载非文本格式
                        xhr.responseType = responseType;
                        if (completeCallback)
                            completeCallback(xhr.response);
                    }
                    else {
                        // 加载非文本格式
                        var data = JSON.parse(xhr.response);
                        if (data.code != null) {
                            /** 服务器错误码处理 */
                            if (data.code == 0) {
                                if (completeCallback)
                                    completeCallback(data.data);
                            }
                            else {
                                if (errorCallback)
                                    errorCallback(data);
                            }
                        }
                        else {
                            if (completeCallback)
                                completeCallback(data);
                        }
                    }
                }
            }
        };
        if (params == null || params == "") {
            xhr.send();
        }
        else {
            xhr.send(paramsStr); // 根据服务器接受数据方式做选择
            // xhr.send(JSON.stringify(params));
        }
    };
    HttpRequest.prototype.deleteCache = function (url) {
        delete urls[url];
        delete reqparams[url];
    };
    return HttpRequest;
}());
exports.HttpRequest = HttpRequest;

cc._RF.pop();